﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.hyrentals.webcommon.configuration;
using System.Web.Routing;
using System.Web.Mvc;

namespace com.hyrentals.webcommon.helpers
{
   public static class RoutingHelper
    {
        #region Register routes
        /// <summary>
        /// Registers routes specified in current routemapping configuration
        /// </summary>
        public static void RegisterRoutes(RouteCollection routes)
        {
            RouteMappingConfiguration config = RouteMappingConfiguration.Current;
            RegisterRoutes(routes, config);
        }

        /// <summary>
        /// Register all routes defined in the RouteMappingConfiguration
        /// </summary>
        /// <param name="routes">RouteCollection to add routes</param>
        /// <param name="config">Routes to register</param>
        public static void RegisterRoutes(RouteCollection routes, RouteMappingConfiguration config)
        {
            if (config == null)
            {
                throw new NullReferenceException("Route mapping configuration not defined.");
            }
            using (routes.GetWriteLock())
            {
                foreach (RouteElement ignoreItem in config.IgnoreRoutes)
                {
                    routes.IgnoreRoute(ignoreItem.Url);
                }

                foreach (RouteElement item in config.Routes)
                {
                    Route route = new Route(item.Url, new MvcRouteHandler());
                    route.Defaults = new RouteValueDictionary();
                    route.Defaults.Add("controller", item.Controller);
                    route.Defaults.Add("action", item.Action);
                    
                    if (item.Defaults != null)
                    {
                        foreach (string key in item.Defaults.AllKeys)
                        {
                            route.Defaults.Add(key, item.Defaults[key].Value);
                        }
                    }
                    if (item.Constraints != null)
                    {
                        route.Constraints = new RouteValueDictionary();
                        foreach (string key in item.Constraints.AllKeys)
                        {
                            route.Constraints.Add(key, item.Constraints[key].Value);
                        }
                    }
                    if (item.Namespace != null)
                    {
                        if (route.DataTokens == null)
                        {
                            route.DataTokens = new RouteValueDictionary();
                        }
                        route.DataTokens["Namespaces"] = new string[] { item.Namespace };

                    }

                    routes.Add(route);
                }
            }
        }
        #endregion
    }
}
